import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:wk_robot2/app/event/DataCallBack.dart';
import 'package:wk_robot2/app/models/Devices.dart';
import 'package:wk_robot2/app/nets/NetWorkManager.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import '../../../../generated/AlphaResponse.pb.dart';
import '../../../../generated/CmQueryPowerData.pb.dart';
import '../../../../generated/GetRobotConfiguration.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../logger/Logger.dart';
import '../../../robot_comm/cmd_const.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../routes/app_pages.dart';
import '../../../storage/StorageManager.dart';
import '../../../style/app_colors.dart';
import '../../../widget/tips.dart';

class IndexViewController extends GetxController {
  var robotNameElected = ''.obs;
  // var robotList = [].obs;
  var batteryCapacity = '0'.obs;
  var batteryIcon = 'assets/images/ic_battery_80.webp'.obs;
  var wifiIcon = 'assets/images/ic_wifi_2.png'.obs;
  var isWifiConnected = false.obs;

  Timer? _timer;

  var myrobots = Device().obs;

  List<String> batteryIconList = [
    'assets/images/ic_battery_10.png',
    'assets/images/ic_battery_20.png',
    'assets/images/ic_battery_40.png',
    'assets/images/ic_battery_60.png',
    'assets/images/ic_battery_80.webp',
    'assets/images/ic_battery_100.png',
  ];

  List<String> wifiSignalIconList = [
    'assets/images/ic_wifi_1.png',
    'assets/images/ic_wifi_2.png',
    'assets/images/ic_wifi_3.png',
    'assets/images/ic_home_wifi_unkonw.webp'
  ];



  // static List<Devices> getMyRobotLists() {
  RxList<Device> localRobotList = RxList<Device>();
  @override
  void onInit() {
    super.onInit();

    localRobotList.value = CommonUtil.getMyRobotLists();

    myrobots.value = CommonUtil.getCurrentSelectedRobot();


    eventBus.on<ProductContentEvent>().listen((event) {
      if(event.code == ROBOT_LIST_HAVE_CHANGED) {

        localRobotList.value = CommonUtil.getMyRobotLists();

        // test begin.
        //重新存储机器人数据.
        //CommonUtil.refreshMyRobotList(robotList.value);
        List<Device> robots = CommonUtil.getMyRobotLists();
        print('======机器人列表更新了 =======> ${json.encode(robots)}');
        // test end.

        if (StorageManager.getStorage().hasData(AppConst.MY_ROBOTS_LIST)) {
            myrobots.value = CommonUtil.getCurrentSelectedRobot();
            loadLocalConnectedRobotsProperties();

            //连接MQTT.
            // 已经有绑定设备,app重新卸载重新安装.
            if(StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY)) {
              try {
                 String currentRobotUserId = StorageManager.getStorage().read(AppConst.BLT_DEVICE_SN_CURRENTLY);
                 print('连接MQTT机器人==== ${currentRobotUserId}');
                 // MqttCommManager().init(currentRobotUserId).then((sucess) {
                 //   print('添加事件....');
                 //   //监听机器人MQTT的在线状态.
                 //   MqttCommManager().addRobotStatusListner(currentRobotUserId, (isOnline) {
                 //     logger.info('机器人: ${currentRobotUserId},在线状态: ${isOnline}');
                 //
                 //     CommonUtil.updateMyRobotLists(currentRobotUserId, {
                 //       "isOnline": isOnline
                 //     });
                 //
                 //   });
                 // });
                MqttCommManager().connectToServer().then((onValue){
                  if(onValue) {
                    //先获取一遍电量数据.
                    MqttCommManager().subscribeMsg(robots, (String id, bool isOnline){
                      logger.info('机器人: ${id},在线状态: ${isOnline}');

                      CommonUtil.updateMyRobotLists(id, {
                        'isOnline':isOnline
                      });
                    });
                  }
                });



              } catch(e) {
                logger.info('MQTT服务不可用1, ${e}');
                Tips.showToast('MQTT服务不可用1. ${e}');
              }

            }
        }
      }
      else if (event.code == ROBOT_BIND_COMPLETED) {
        freshBatteryPowAndWifi();
      }
    });

    if(StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY)) {
      try {
        String currentRobotUserId = StorageManager.getStorage().read(AppConst.BLT_DEVICE_SN_CURRENTLY);
        // MqttCommManager().init(currentRobotUserId).then((sucess) {
        //   //监听机器人MQTT的在线状态.
        //   MqttCommManager().addRobotStatusListner(currentRobotUserId, (isOnline) {
        //     logger.info('机器人: ${currentRobotUserId},在线状态: ${isOnline}');
        //     print('添加事件....22222');
        //     CommonUtil.updateMyRobotLists(currentRobotUserId, {
        //       "isOnline": isOnline
        //     });
        //
        //   });
        // });
        MqttCommManager().connectToServer().then((onValue){
          if(onValue){
            MqttCommManager().subscribeMsg( CommonUtil.getMyRobotLists(), (String id, bool isOnline){
              logger.info('机器人: ${id},在线状态: ${isOnline}');
              CommonUtil.updateMyRobotLists(id, {
                 'isOnline':isOnline
              });
            });
          }
        });



      } catch(e) {
        logger.info('MQTT服务不可用2, ${e}');
        Tips.showToast('MQTT服务不可用2. ${e}');
      }

    }

    retrieveRobots();
  }

  @override
  void onReady() {
    super.onReady();
    // todo 检查蓝牙和location是否已经开启. 如果开启,启动机器人扫描.
    startTimer();

    loadLocalConnectedRobotsProperties();

  }


  void loadLocalConnectedRobotsProperties() {
    if (myrobots.value!.powerValue != null) {
      batteryCapacity.value = myrobots.value!.powerValue != null ? myrobots.value!.powerValue.toString() : '10';
      int capacity = int.parse(batteryCapacity.value);
      if (capacity <= 10) {
        batteryIcon.value = batteryIconList[0];
      }
      else if ((capacity >= 10 && capacity < 20)) {
         batteryIcon.value = batteryIconList[1];
      } else if (capacity >= 20 && capacity < 40) {
        batteryIcon.value = batteryIconList[2];
      } else if (capacity >= 40 && capacity < 60) {
        batteryIcon.value = batteryIconList[3];
      } else if (capacity >= 60 &&  capacity < 80) {
        batteryIcon.value = batteryIconList[4];
      } else if (capacity >= 80 &&  capacity <= 100) {
        batteryIcon.value = batteryIconList[5];
      }
    }


    if (myrobots.value!.wifiSingle != null) {
        if (myrobots.value!.wifiSingle == 0 || myrobots.value!.wifiSingle == 1) {
           //week
          wifiIcon.value = wifiSignalIconList[0];
        } else if (myrobots.value!.wifiSingle == 2 ) {
          // common
          wifiIcon.value = wifiSignalIconList[1];
        } else if (myrobots.value!.wifiSingle == 3 || myrobots.value!.wifiSingle == 4) {
          // stronger
          wifiIcon.value = wifiSignalIconList[2];

        } else { // unknow
          wifiIcon.value = wifiSignalIconList[3];
        }


    }


    if (myrobots.value!.isWifiConnected != null)
      isWifiConnected.value = myrobots.value!.isWifiConnected!;

    if (myrobots.value != null && myrobots.value.robotUserId != null) {
      String robotId = myrobots.value.robotUserId!;
      robotNameElected.value = robotId.substring(robotId.length - 4, robotId.length);
    }



    // batteryIcon
    // wifiIcon
  }


  @override
  void onClose() {
    stopTimer();
    super.onClose();
  }


  void startTimer() {
    _timer = Timer.periodic(Duration(seconds: 30), (Timer timer) {
      freshBatteryPowAndWifi();

    });
  }

  void stopTimer() {
    _timer?.cancel();
    _timer = null;

  }



  List<dynamic> getRobotFunctionList() {
    return [
      {
        'name':'动作广场',
        'icon': 'assets/images/ic_square.webp',
        'type': 'actionSquare'
      },
      {
        'name':'视频通话',
        'icon': 'assets/images/ic_video.webp',
        'type': 'videoTalking'
      },
      {
        'name':'图形编辑',
        'icon': 'assets/images/ic_program.webp',
        'type': 'imageEdition'
      },
      {
        'name':'绘本伴读',
        'icon': 'assets/images/ic_book.webp',
        'type': 'readingCompany'
      },
      {
        'name':'英语会话',
        'icon': 'assets/images/ic_Eng_conversation.webp',
        'type': 'conversation'
      },
      {
        'name':'闹钟提醒',
        'icon': 'assets/images/ic_alarm.webp',
        'type': 'clockReminder'
      },
      {
        'name':'自主智能',
        'icon': 'assets/images/ic_AI.webp',
        'type': 'selfAi'
      },
      {
        'name':'动作设计',
        'icon': 'assets/images/ic_choregraphy.webp',
        'type': 'actionDesign'
      }

    ];

  }



  // 获取用户绑定的机器人列表.
  void retrieveRobots({bool fromBindPage = false}) {
       NetWorkManager.getInstance().requestBussiness(NetWorkManager.GET_MY_ROBOT_LIST, {},
         NetWorkManager.methodGET, DataCallBack(
            businessCallBack:(v) {
                if (v == null) {
                   v = [];
                }


                // test begin.
                //重新存储机器人数据.
                //CommonUtil.refreshMyRobotList(robotList.value);
                List<Device> robots = CommonUtil.getMyRobotLists();
                print('======本地列表 =======> ${json.encode(robots)}');
                // test end.

                if (!v.isEmpty) {
                   if (fromBindPage) { // 如果从绑定页面过来,默认第一个设备就是当前连接设备.
                     // 将绑定列表中的第一个设备,作为用户当前要连接的设备.
                     StorageManager.getStorage().write(AppConst.BLT_DEVICE_SN_CURRENTLY, v[0]['robotUserId']);
                     String robotUserId = v[0]['robotUserId'] as String;

                     CommonUtil.refreshMyRobotList(v);
                     CommonUtil.switch2FavorRobot(robotUserId);



                   } else { // 页面初始化数据而来,需要找出当前连接得设备状态.
                     String deviceSN = StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY) ?
                                  StorageManager.getStorage().read(AppConst.BLT_DEVICE_SN_CURRENTLY): '';

                     CommonUtil.refreshMyRobotList(v);

                     if (deviceSN == '') {
                       CommonUtil.switch2FavorRobot(v[0]['robotUserId']);

                     } else {
                       CommonUtil.switch2FavorRobot(deviceSN);
                     }
                   }


                } else { //清空本地机器人列表.
                  // StorageManager.getStorage().write(AppConst.MY_ROBOTS_LIST,json.encode([]));
                  CommonUtil.clearAllRobots();
                }

               /* //刷新我的页面.
                MineViewController mineViewController = GetInstance().find<MineViewController>();
                if (mineViewController != null) {
                 mineViewController.freshDevice(v);
                }*/

                myrobots.value = CommonUtil.getCurrentSelectedRobot();
            }
        ));

  }


  void changeCurrentConnectionDevice(Device data) {
        CommonUtil.switch2FavorRobot(data.robotUserId!);
  }


  //绑定机器人.
  void bindRobot()  async {
    // Get.toNamed(Routes.POWER_ONING);
    CommonUtil.bindDevices();
  }


  void freshBatteryPowAndWifi() {
    print('开始获取电量和wifi: ${DateTime.now().toLocal().toString()}');
    if(StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY) && CommonUtil.getLoginUserId() != 0) {
      CmQueryPowerDataRequest request = CmQueryPowerDataRequest();
      MqttCommManager().sendCmd(CmdConst.IM_QUERY_ROBOT_POWER_REQUEST, request, (AlphaResponse msg) {
        CmQueryPowerDataResponse response = CmQueryPowerDataResponse.fromBuffer(msg.bodyData);
        logger.info("查询电量结果： ${response}");


        CommonUtil.freshRobotMQTTInfo(CommonUtil.getBltDeviceSN(),
            response.powerValue, response.levelStatus, response.isWifiOpen, response.wifiSingle,
            response.isWifiConnected, response.version, response.cloundVersion);

        //获取wifi名字.
        GetRobotConfigurationRequest request = GetRobotConfigurationRequest();
        MqttCommManager().sendCmd(CmdConst.IM_GET_ROBOT_CONFIG_REQUEST, request, (AlphaResponse msg) {
          GetRobotConfigurationResponse configurationResponse  = GetRobotConfigurationResponse.fromBuffer(msg.bodyData);
          CommonUtil.updateMyRobotLists(CommonUtil.getBltDeviceSN(), {
            'wifiName': configurationResponse.wifiname
          });

        });



      });
    }


  }






  void gotoVideoLiveView() {
    // todo 查询绑定机器人正常后，把这块注释去掉
    //if(CommonUtil.getBltDeviceSN() == ""){
    //   CommonWidgets.showConfirmDialog(Get.context!, "请绑定悟空机器人", "绑定后可以使用各项技能", "绑定", "取消", DataCallBack(
    //       confirmCallBack: (v) {
    //         logger.info('agree ...');
    //         Get.toNamed(Routes.BINDING);
    //         //StorageManager.getStorage().write(AppConst.storage_key_user_protocol_has_read, true);
    //       },
    //       cancleCallBack: (v) {
    //         logger.info('disagree ...');
    //         //StorageManager.getStorage().write(AppConst.storage_key_user_protocol_has_read, false);
    //       }
    //   ));
    // }else{
       Get.toNamed(Routes.VIEWO_LIVE);
    // }

  }


  List<Widget> renderItemsForLess5 () {
    List<Widget>  listView = [];

    localRobotList.value.forEach((item) {

      listView.add(Container(
          padding: EdgeInsets.all(5),
          child: GestureDetector(
            onTap: () {
              changeCurrentConnectionDevice(item);
              Get.back();
            },
            child: Container(
              color: Colors.white.withOpacity(0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Image.asset('assets/images/ic_avatar_online.png',width: 80.w,height: 80.h,),
                      SizedBox(width: 28.w,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Text('悟空',style: TextStyle(fontSize: 30.sp,color: Colors.white.withOpacity(0.8))),
                              SizedBox(width: 14.w),
                              Container(
                                padding: EdgeInsets.only(left: 13.w,right: 13.w),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(20)),
                                    color: AppColors.robot_online_status_color
                                ),
                                child: Text(item.isOnline ? '在线': '离线',style: TextStyle(fontSize: 22.sp,color: AppColors.Page_Title_Color),),
                              )
                            ],
                          ),
                          Text('${item.robotUserId}',style: TextStyle(fontSize: 24.sp,color: Colors.white.withOpacity(0.5)))

                        ],
                      )
                    ],
                  ),
                  item.selected == true ? Image.asset('assets/images/ic_robots_selected.webp',width: 40.w,height: 40.h,color: Colors.white.withOpacity(0.8),) : SizedBox()
                ],
              ),
            ),
          ),
        ));
      listView.add(SizedBox(height: 16.h));
      listView.add(Divider(color: Colors.white.withOpacity(0.2),height:5,indent: 6.0,endIndent: 6.0));

    });

    return listView;
  }




}